package edu.pku.hawk.controller.util;

import java.util.concurrent.TimeoutException;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageListener;
import javax.jms.ObjectMessage;
import javax.jms.Session;
import javax.jms.TextMessage;

public class MConsumerQueue extends MQueue {

	private MessageConsumer consumer;

	public MConsumerQueue(String queueName, Session session, MessageConsumer consumer) {
		super(queueName, session);
		this.consumer = consumer;
	}

	public String getText() throws JMSException, TimeoutException {
		TextMessage message = (TextMessage) consumer.receive();
		return message.getText();
	}

	public String getText(long timeout) throws JMSException, TimeoutException {
		Message message =  consumer.receive(timeout);
		return (message != null) ? ((TextMessage) message).getText() : null;
	}
	
	public String getTextNoWait() throws JMSException, TimeoutException {
		Message message = consumer.receiveNoWait();
		return (message != null) ? ((TextMessage) message).getText() : null;
	}

	public Object getObject() throws JMSException, TimeoutException {
		ObjectMessage message = (ObjectMessage) consumer.receive();
		return message.getObject();
	}
	
	public Object getObjectNoWait() throws JMSException, TimeoutException {
		Message message = consumer.receiveNoWait();
		return (message != null) ? ((ObjectMessage) message).getObject() : null;
	}

	public Object getObject(long timeout) throws JMSException, TimeoutException {
		Message message = consumer.receive(timeout);
		return (message != null) ? ((ObjectMessage) message).getObject() : null;
	}

	public void setMessageListener(MessageListener listener) throws JMSException {
		this.consumer.setMessageListener(listener);
	}

	public int clear() throws JMSException {
		int i = 0;
		while (this.consumer.receive(50) != null)
			i++;
		return i;
	}

	public void close() throws JMSException{
		if (this.consumer != null)
			this.consumer.close();
	}

}
